# conding=utf-8
from django.shortcuts import render
from django.http import HttpResponse
from QipaoProject import view

# 获取后台管理者的用户名与密码
def get_accounts():
    # 读出account.txt中的每一行（每一行的3个字符串代表用户的：
    # 用户名、密码、权限）
    f = open('QipaoProject/actions/accounts.txt', 'r')
    strings = f.readlines()
    accounts = []
    for string in strings:
        if string[-1] == '\n':
            string = string[:-1]
        # 将每一行剥离成3个子字符串
        account = string.split('\t')
        accounts.append(account)
    return accounts


'''
===============
    API函数
===============

'''
# 进行登录操作（处理请求login.do）
def login(request):
    user = None
    # 获取表单中的用户名与密码
    username = request.POST.get('username')
    password = request.POST.get('password')
    # 加载本地保存的用户名与密码
    accounts = get_accounts()
    # 进行匹配
    flag = False
    for account in accounts:
        # 如果匹配成功！登录成功！将用户信息保存在session中
        if username == account[0] and password == account[1]:
            user = {}
            user['username'] = username
            user['password'] = password
            user['rank'] = account[2]
            request.session['user'] = user
            # 跳转到分类界面
            return view.to_classify_page(request)
    # 如果登录失败
    return render(request, 'login.html')

# 检查Session中是否有用户信息
def checkSession(request):
    user = request.session.get('user', None)
    return user

# 用户注销登录
def logout(request):
    data = {}
    user = request.session.get('user', None)
    if user != None:
        del request.session['user']
        data['message'] = user['username'] +'已经退出登录……'
    else:
        data['message'] = '您还未登录！'
    data['url'] = '/loginPage'
    data['action'] = '返回登录界面'
    return render(request, 'result.html', data)
